<template>
  <div class="record-management">
    <div class="record-header">
      <h3>数据存证</h3>
      <el-button type="primary" @click="showAddDialog">添加存证</el-button>
    </div>

    <!-- 存证记录列表 -->
    <el-table :data="records" style="width: 100%" v-loading="loading">
      <el-table-column prop="record_id" label="存证ID" width="180"></el-table-column>
      <el-table-column prop="data_type" label="数据类型" width="120">
        <template slot-scope="scope">
          <el-tag :type="getDataTypeTag(scope.row.data_type)">
            {{ getDataTypeLabel(scope.row.data_type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="data_hash" label="数据哈希" width="280"></el-table-column>
      <el-table-column prop="block_hash" label="区块哈希" width="280"></el-table-column>
      <el-table-column prop="timestamp" label="存证时间" width="180"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewDetails(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <!-- 在操作列后添加验证状态列 -->
      <el-table-column label="验证状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.chain_valid ? 'success' : 'danger'">
            {{ scope.row.chain_valid ? '有效' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 在现有表格中添加存证验证列 -->
      <el-table-column label="区块链验证" width="120">
        <template slot-scope="scope">
          <el-button 
            @click="showBlockDetail(scope.row)"
            type="text">查看存证
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加存证对话框 -->
    <el-dialog title="添加存证" :visible.sync="dialogVisible" width="500px">
      <el-form :model="recordForm" :rules="rules" ref="recordForm" label-width="100px">
        <el-form-item label="数据类型" prop="data_type">
          <el-select v-model="recordForm.data_type" placeholder="请选择数据类型">
            <el-option label="批次信息" value="batch"></el-option>
            <el-option label="质检记录" value="quality"></el-option>
            <el-option label="物流记录" value="logistics"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据内容" prop="data_content">
          <el-input type="textarea" v-model="recordForm.data_content" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRecord">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'BlockchainRecordManagement',
  data() {
    return {
      loading: false,
      records: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      recordForm: {
        data_type: '',
        data_content: ''
      },
      rules: {
        data_type: [
          { required: true, message: '请选择数据类型', trigger: 'change' }
        ],
        data_content: [
          { required: true, message: '请输入数据内容', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchRecords()
  },
  methods: {
    async fetchRecords() {
      this.loading = true
      try {
        const response = await axios.get('/api/blockchain/records', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize
          }
        })
        this.records = response.data.items
        this.total = response.data.total
      } catch (error) {
        this.$message.error('获取区块链记录失败')
        console.error('获取区块链记录失败:', error)
      } finally {
        this.loading = false
      }
    },
    async handleCurrentChange(page) {
      this.currentPage = page
      await this.fetchRecords()
    },
    openAddDialog() {
      this.dialogVisible = true
      this.recordForm = {
        data_type: '',
        data_content: ''
      }
    },
    async submitRecord() {
      try {
        await this.$refs.recordForm.validate()
        
        // 处理JSON数据内容
        let contentData
        try {
          contentData = JSON.parse(this.recordForm.data_content)
        } catch (e) {
          this.$message.error('数据内容必须是有效的JSON格式')
          return
        }
        
        const response = await axios.post('/api/blockchain/records', {
          data_type: this.recordForm.data_type,
          data_content: contentData
        })
        
        this.$message.success('区块链记录创建成功')
        this.dialogVisible = false
        this.fetchRecords()
      } catch (error) {
        this.$message.error('创建区块链记录失败')
        console.error('创建区块链记录失败:', error)
      }
    },
    async viewDetails(record) {
      try {
        const response = await axios.get(`/api/blockchain/records/${record.record_id}`)
        const detailData = response.data
        
        // 格式化JSON数据以便显示
        const formattedContent = JSON.stringify(detailData.data_content, null, 2)
        
        this.$alert(formattedContent, '记录详情', {
          dangerouslyUseHTMLString: false,
          customClass: 'record-detail-dialog'
        })
      } catch (error) {
        this.$message.error('获取记录详情失败')
        console.error('获取记录详情失败:', error)
      }
    },
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return date.toLocaleString()
    },
    getDataTypeLabel(type) {
      const types = {
        batch: '批次信息',
        quality: '质检记录',
        logistics: '物流记录'
      }
      return types[type] || type
    },
    getDataTypeTag(type) {
      const tags = {
        batch: 'primary',
        quality: 'success',
        logistics: 'warning'
      }
      return tags[type] || 'info'
    },
    // 新增存证详情弹窗
    async showBlockDetail(row) {
      const { data } = await this.$http.get(`/api/blockchain/records/${row.record_id}`)
      this.$alert(`
        数据哈希：${data.data_hash}
        区块哈希：${data.block_hash}
        存证时间：${data.timestamp}
      `, '区块链存证详情')
    }
  }
}
</script>

<style scoped>
.record-management {
  padding: 20px;
}
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.record-header h3 {
  margin: 0;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.valid {
  color: #67C23A;
}
.invalid {
  color: #F56C6C;
}
</style>
<style>
.record-detail-dialog .el-message-box__content {
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  font-family: monospace;
}
</style>

